package namespace

import (
	"context"
	"gitee/yinlai/kms-backend/config"
	"gitee/yinlai/kms-backend/controllers"
	"gitee/yinlai/kms-backend/utils/logs"
	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"net/http"
)

func Create(r *gin.Context) {
	logs.Debug(nil, "添加namespace")

	clientset, basicInfo, err := controllers.BasicInit(r, nil)
	returnData := config.ReturnData{}
	if err != nil {
		returnData.Message = err.Error()
		returnData.Status = 400
		r.JSON(http.StatusOK, returnData)
		return
	}

	//// 声明一个集群的配置
	//basicInfo := controllers.BasicInfo{}
	//// 在config文件中定义的一个公共的数据返回对象
	//returnData := config.NewReturnData()
	//if err := r.ShouldBindJSON(&basicInfo); err != nil {
	//	msg := "请求出现错误：" + err.Error()
	//	returnData.Status = 400
	//	returnData.Message = msg
	//	r.JSON(200, returnData)
	//	return
	//}
	//// 获取kubeconfig
	//kubeconfig := config.ClusterKubeconfig[basicInfo.ClusterId]
	//
	//restConfig, err := clientcmd.RESTConfigFromKubeConfig([]byte(kubeconfig))
	//if err != nil {
	//	logs.Error(map[string]interface{}{"id": basicInfo.ClusterId, "msg": err.Error()}, "解析kubeconfig错误")
	//	msg := "解析kubeconfig错误：" + err.Error()
	//	returnData.Status = 400
	//	returnData.Message = msg
	//	r.JSON(http.StatusOK, returnData)
	//	return
	//}
	//clientset, err := kubernetes.NewForConfig(restConfig)
	//if err != nil {
	//	logs.Error(map[string]interface{}{"id": basicInfo.ClusterId, "msg": err.Error()}, "创建clientset失败")
	//	msg := "创建clientset失败：" + err.Error()
	//	returnData.Status = 400
	//	returnData.Message = msg
	//	r.JSON(http.StatusOK, returnData)
	//	return
	//}
	var namespace corev1.Namespace
	namespace.Name = basicInfo.Name
	_, err = clientset.CoreV1().Namespaces().Create(context.TODO(), &namespace, metav1.CreateOptions{})
	if err != nil {
		logs.Error(map[string]interface{}{"id": basicInfo.ClusterId, "msg": err.Error()}, "创建Namespace失败")
		msg := "创建Namespace失败：" + err.Error()
		returnData.Status = 400
		returnData.Message = msg
	} else {
		returnData.Message = "创建成功"
		returnData.Status = 200
	}
	r.JSON(http.StatusOK, returnData)
}
